package com.lap.framework.user.interceptor;

import com.lap.framework.user.UserConstants;
import com.lap.framework.user.UserHandler;
import com.lap.framework.user.domain.User;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <pre>
 * 用户拦截,需要在每个使用到的项目中添加,不然拿不到用户数据.
 * 使用方式: 注册
 * </pre>
 *
 * @author Shuisheng.Lao
 * @version 1.0.0
 */
public class UserInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userIdStr = request.getHeader(UserConstants.REQUEST_USER_ID);
        String username = request.getHeader(UserConstants.REQUEST_USER_NAME);
        if (isNotEmpty(userIdStr)) {
            try {
                Integer userId = Integer.valueOf(userIdStr);
                UserHandler.set(new User(userId, username));
            } catch (NumberFormatException e) {
                throw e;
            }
        }
        return super.preHandle(request, response, handler);
    }

    /**
     * 判断字符串是否为空
     *
     * @param str 字符串入参
     * @return 不为空:true,为空:false
     */
    private boolean isNotEmpty(String str) {
        return (str != null && !"".equals(str));
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHandler.remove();
        super.afterCompletion(request, response, handler, ex);
    }

}
